package exercise17;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import java.util.Scanner;
import java.io.*;

public class Exercise17_4  extends JFrame{
	
	private JTextArea jta = new JTextArea();
	private JScrollPane scrollpane = new JScrollPane(jta);
	private JTextField jtf = new JTextField("F:\\JStudy\\JavaBase\\src\\chapter17\\ButtonDemo.java");
	private Border lineborder = new LineBorder(Color.BLACK, 1);
	
	public static void displayText(String filePath, JTextArea jta) throws FileNotFoundException{
		if (jta == null) return;
		jta.setText("");
		File file = new File(filePath);
		Scanner input = new Scanner(file);
		if (file.exists() && file.isFile()) {
			while (input.hasNext()) {
				jta.append(input.nextLine());
				jta.append("\n");
			}
			input.close();
		}
		else{
			System.out.println("File isn't exists!");
		}
	}
	
	public Exercise17_4(){
		setLayout(new BorderLayout(5, 5));
		
		jta.setLineWrap(true);
		jta.setWrapStyleWord(true);
		scrollpane.setBorder(lineborder);
		add(scrollpane, BorderLayout.CENTER);
		
		JPanel jpInput = new JPanel();
		JLabel jlbFileName = new JLabel("Filename ");
		JButton jbtView = new JButton("View");
		Font boldFont = new Font("TimesRoman", Font.BOLD, 10);
		jbtView.setFont(boldFont);
		jpInput.add(jlbFileName);
		jpInput.add(jtf);
		jpInput.add(jbtView);
		jpInput.setBorder(lineborder);
		
		add(jpInput, BorderLayout.SOUTH);
		
		jbtView.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e){;
				try {
					displayText(jtf.getText(), jta);
				} catch (FileNotFoundException e1) {
//					e1.printStackTrace();
					System.out.println("File isn't exists!");
				}
			}
		});
		
		jtf.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					displayText(jtf.getText(), jta);
				} catch (FileNotFoundException e1) {
//					e1.printStackTrace();
					System.out.println("File isn't exists!");
				}	
			}
		});
	
	}
	
	
	public static void main(String[] args) {
		Exercise17_4 frame = new Exercise17_4();
		frame.setTitle("Exercise17_4");
		frame.setSize(700, 200);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setVisible(true);
		
	}
	

}
